package com.shop.servlet;

import com.shop.model.CartItem;
import com.shop.model.Course;
import com.shop.service.CourseService;
import com.shop.service.ICourseService;
import com.shop.service.StudentService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


// File: src/com/shop/servlet/CartServlet.java
@WebServlet("/cart")
public class CartServlet extends HttpServlet {
    ICourseService icourseService = new CourseService();
    private StudentService studentService = new StudentService();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        req.setCharacterEncoding("UTF-8");

        String studentId = req.getParameter("studentId");
        String courseId = req.getParameter("courseId");
        System.out.println("CartServlet:33:" + studentId + " " + courseId);//调试

        //获取课程和学生信息
        Course course = icourseService.searchCourse1(courseId);

        if (course == null) {
            throw new RuntimeException("课程不存在");
        }

        try {
            //将课程信息添加到购物车
            HttpSession session = req.getSession();
            List<CartItem> cart = (List<CartItem>) session.getAttribute("cart");
            if (cart == null) {
                cart = new ArrayList<>();
                session.setAttribute("cart", cart);
            }

            boolean found = false;
            //检查购物车中是否已经存在该课程
            for (CartItem item : cart) {
                if (item.getCourse().getCourseId().equals(courseId)) {
                    item.increaseQuantity();
                    found = true;
                    break;
                }
            }

            // 如果不存在，则添加新项
            if (!found) {
                cart.add(new CartItem(course,1));
            }

            // 重定向到购物车页面
            session.setAttribute("studentId", studentId);
            resp.sendRedirect("cart.jsp");


        } catch (Exception e) {
            req.setAttribute("error", e.getMessage());
            req.getRequestDispatcher("/error.jsp").forward(req, resp);
        }
    }

}



